<template>
  <div class="upload-container">
    <h2>多文件上传示例</h2>

    <!-- 上传区域 -->
    <div class="upload-area" 
         @drop.prevent="handleDrop"
         @dragover.prevent="handleDragOver"
         @dragleave.prevent="handleDragLeave"
         :class="{ 'drag-over': isDragOver }">
      
      <!-- 上传按钮和说明 -->
      <div class="upload-header">
        <el-upload
          ref="upload"
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleFileChange"
          multiple>
          <el-button type="primary" icon="el-icon-upload">选择文件</el-button>
        </el-upload>
        <div class="upload-tips">
          <p>支持拖拽上传，单个文件不超过50MB</p>
          <p>支持格式：.jpg, .png, .pdf, .doc, .docx, .xls, .xlsx</p>
        </div>
      </div>

      <!-- 文件列表 -->
      <div class="file-list" v-if="fileList.length > 0">
        <div v-for="(file, index) in fileList" 
             :key="index"
             class="file-item"
             :class="{ 'upload-success': file.status === 'success', 
                      'upload-error': file.status === 'error' }">
          <!-- 文件图标 -->
          <i :class="getFileIcon(file.name)" class="file-icon"></i>
          
          <!-- 文件信息 -->
          <div class="file-info">
            <div class="file-name">{{ file.name }}</div>
            <div class="file-size">{{ formatFileSize(file.size) }}</div>
          </div>
          
          <!-- 状态显示 -->
          <div class="file-status">
            <template v-if="file.status === 'error'">
              <el-button 
                type="text" 
                icon="el-icon-refresh" 
                @click="retryUpload(file)"
                class="retry-btn">
                重试
              </el-button>
            </template>
            <template v-else-if="file.status === 'uploading'">
              <span class="uploading-text">
                <i class="el-icon-loading"></i>
                正在上传...
              </span>
            </template>
            <template v-else-if="file.status === 'success'">
              <i class="el-icon-check success"></i>
            </template>
            <template v-else>
              <el-button 
                type="text" 
                icon="el-icon-delete"
                @click="removeFile(index)">
              </el-button>
            </template>
          </div>
        </div>
      </div>

      <!-- 上传操作按钮 -->
      <div class="upload-actions" v-if="fileList.length > 0">
        <el-button 
          type="primary" 
          @click="uploadFiles" 
          :loading="uploading"
          :disabled="fileList.length === 0">
          {{ uploading ? `正在上传(${uploadingCount}/${fileList.length})` : '开始上传' }}
        </el-button>
        <el-button @click="clearFiles" :disabled="uploading">清空列表</el-button>
      </div>
    </div>

    <!-- 上传统计 -->
    <div class="upload-stats" v-if="fileList.length > 0">
      <div class="stat-item">
        <span>总文件数：</span>
        <span>{{ fileList.length }}</span>
      </div>
      <div class="stat-item">
        <span>总大小：</span>
        <span>{{ totalSize }}</span>
      </div>
      <div class="stat-item">
        <span>已上传：</span>
        <span>{{ uploadedCount }}/{{ fileList.length }}</span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'MultiFileUpload',
  
  data() {
    return {
      fileList: [],
      isDragOver: false,
      uploading: false,
      acceptedTypes: [
        'image/jpeg', 
        'image/png', 
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      ],
      maxConcurrent: 3, // 最大并行上传数
      uploadingCount: 0  // 当前正在上传的文件数
    };
  },

  computed: {
    totalSize() {
      const total = this.fileList.reduce((acc, file) => acc + file.size, 0);
      return this.formatFileSize(total);
    },
    
    uploadedCount() {
      return this.fileList.filter(file => file.status === 'success').length;
    },
    
  },

  methods: {
    handleFileChange(file) {
      if (!this.validateFile(file)) return;
      
      this.fileList.push({
        ...file,
        status: 'ready',
        percentage: 0
      });
    },

    handleDrop(e) {
      this.isDragOver = false;
      const files = Array.from(e.dataTransfer.files);
      files.forEach(file => {
        const fileObj = {
          raw: file,
          name: file.name,
          size: file.size,
          type: file.type,
          status: 'ready',
          percentage: 0
        };
        
        if (this.validateFile(fileObj)) {
          this.fileList.push(fileObj);
        }
      });
    },

    handleDragOver() {
      this.isDragOver = true;
    },

    handleDragLeave() {
      this.isDragOver = false;
    },

    validateFile(file) {
      const fileType = file.raw ? file.raw.type : file.type;
      
      // 检查文件类型
      if (!this.acceptedTypes.includes(fileType)) {
        // 如果文件类型不在允许列表中，尝试通过扩展名判断
        const ext = file.name.split('.').pop().toLowerCase();
        const extMap = {
          'jpg': 'image/jpeg',
          'jpeg': 'image/jpeg',
          'png': 'image/png',
          'pdf': 'application/pdf',
          'doc': 'application/msword',
          'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          'xls': 'application/vnd.ms-excel',
          'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        };
        
        if (!extMap[ext] || !this.acceptedTypes.includes(extMap[ext])) {
          this.$message.error(`不支持的文件类型: ${file.name}`);
          return false;
        }
      }
      
      // 检查文件大小
      const fileSize = file.raw ? file.raw.size : file.size;
      if (fileSize > 50 * 1024 * 1024) {
        this.$message.error(`文件过大: ${file.name}`);
        return false;
      }

      // 检查重复文件
      if (this.fileList.some(f => f.name === file.name)) {
        this.$message.warning(`文件已存在: ${file.name}`);
        return false;
      }

      return true;
    },

    async uploadFiles() {
      if (this.uploading) return;
      this.uploading = true;
      this.uploadingCount = 0;

      try {
        const readyFiles = this.fileList.filter(file => file.status === 'ready');
        const uploadPromises = [];
        
        // 创建上传队列
        const uploadQueue = async () => {
          while (readyFiles.length > 0 && this.uploadingCount < this.maxConcurrent) {
            const file = readyFiles.shift();
            this.uploadingCount++;
            
            const uploadPromise = this.uploadFile(file)
              .finally(() => {
                this.uploadingCount--;
                // 继续处理队列中的文件
                if (readyFiles.length > 0) {
                  uploadQueue();
                }
              });
            
            uploadPromises.push(uploadPromise);
          }
        };

        // 启动初始的并行上传
        await uploadQueue();
        
        // 等待所有文件上传完成
        await Promise.all(uploadPromises);
        
        // 上传完成后的处理
        const failedCount = this.fileList.filter(file => file.status === 'error').length;
        if (failedCount > 0) {
          this.$message.warning(`上传完成，${failedCount}个文件上传失败`);
        } else {
          this.$message.success('所有文件上传成功');
        }

      } catch (error) {
        console.error('上传过程出错:', error);
        this.$message.error('上传过程出错，请重试');
      } finally {
        this.uploading = false;
        this.uploadingCount = 0;
      }
    },

    uploadFile(file) {
      return new Promise((resolve, reject) => {
        if (file.status !== 'ready') {
          resolve();
          return;
        }

        file.status = 'uploading';
        
        // 模拟上传延迟
        setTimeout(() => {
          try {
            // 模拟随机上传结果
            const isSuccess = Math.random() > 0.1;
            file.status = isSuccess ? 'success' : 'error';
            
            if (file.status === 'error') {
              file.error = '上传失败，请重试';
              reject(new Error('Upload failed'));
            } else {
              resolve();
            }
          } catch (error) {
            file.status = 'error';
            file.error = '上传过程出错';
            reject(error);
          }
        }, 1500); // 模拟1.5秒的上传时间
      });
    },

    // 添加重试功能
    async retryUpload(file) {
      if (file.status !== 'error') return;
      
      file.status = 'ready';
      file.percentage = 0;
      file.error = null;
      
      try {
        await this.uploadFile(file);
        this.$message.success(`文件 ${file.name} 重新上传成功`);
      } catch (error) {
        this.$message.error(`文件 ${file.name} 重新上传失败`);
      }
    },

    removeFile(index) {
      this.fileList.splice(index, 1);
    },

    clearFiles() {
      this.fileList = [];
    },

    showError(file) {
      this.$message.error(file.error || '上传失败');
    },

    formatFileSize(bytes) {
      if (bytes === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;
    },

    getFileIcon(fileName) {
      const ext = fileName.split('.').pop().toLowerCase();
      const icons = {
        jpg: 'el-icon-picture',
        jpeg: 'el-icon-picture',
        png: 'el-icon-picture',
        pdf: 'el-icon-document',
        doc: 'el-icon-document',
        docx: 'el-icon-document',
        xls: 'el-icon-document',
        xlsx: 'el-icon-document'
      };
      return icons[ext] || 'el-icon-document';
    }
  }
};
</script>

<style scoped>
.upload-container {
  padding: 20px;
}

h2 {
  color: #2c3e50;
  margin-bottom: 20px;
}

.upload-area {
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  padding: 20px;
  background: #fff;
  transition: all 0.3s;
}

.upload-area.drag-over {
  border-color: #409eff;
  background: #ecf5ff;
}

.upload-header {
  text-align: center;
  margin-bottom: 20px;
}

.upload-tips {
  margin-top: 10px;
  color: #909399;
  font-size: 14px;
}

.file-list {
  margin: 20px 0;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 10px;
  transition: all 0.3s;
}

.file-item:hover {
  background: #f5f7fa;
}

.file-icon {
  font-size: 24px;
  color: #909399;
  margin-right: 10px;
}

.file-info {
  flex: 1;
}

.file-name {
  font-size: 14px;
  color: #303133;
  margin-bottom: 4px;
}

.file-size {
  font-size: 12px;
  color: #909399;
}

.file-status {
  min-width: 80px; /* 调整宽度以适应文字 */
  text-align: right;
  padding-right: 10px;
}

.success {
  color: #67c23a;
}

.error {
  color: #f56c6c;
  cursor: pointer;
}

.upload-actions {
  text-align: center;
  margin-top: 20px;
}

.upload-stats {
  margin-top: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
  display: flex;
  justify-content: space-around;
}

.stat-item {
  color: #606266;
}

.stat-item span:first-child {
  margin-right: 5px;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .file-progress {
    width: 100px;
  }

  .upload-stats {
    flex-direction: column;
    gap: 10px;
  }
}

.retry-btn {
  color: #f56c6c;
}

.retry-btn:hover {
  color: #ff7875;
}

/* 添加上传中状态的样式 */
.file-item.uploading {
  background-color: #f5f7fa;
}

/* 成功状态的样式 */
.file-item.upload-success {
  background-color: #f0f9eb;
}

/* 错误状态的样式 */
.file-item.upload-error {
  background-color: #fef0f0;
}

/* 移除进度条相关样式 */
.uploading-text {
  color: #409EFF;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
}
</style>